/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.ycl.data.exchange.runner.proxy;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;

public class JettyClient {

    private static Logger logger = Logger.getLogger(JettyClient.class);

    //post提交，返回content
    public String postSendReturnContent(String url, String responseString) {
        url = getRightUrl(url);
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String rs = "";
        try {
            httpClient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost(url);
            ByteArrayEntity entity = new ByteArrayEntity(responseString.getBytes());
//            InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(responseString.getBytes()), -1);
            entity.setContentType("binary/octet-stream");
            entity.setChunked(true);
            httppost.setEntity(entity);
            response = httpClient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == 200) {
                rs = HttpResponseParser.getResponseContent(response);
            } else {
                rs = "";
            }
        } catch (Exception ex) {
            logger.error(url + " JettyClient send error!" + ex.getMessage() + "|" + ex.getLocalizedMessage());
            return "";
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException ex) {
                logger.error(ex.getMessage(), ex);
            }
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
        return rs;
    }

    public String postSendReturnContent(String url, String taskType, String msgType, String uid, String seq) {
        url = getRightUrl(url);
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String rs = "";
        try {
            httpClient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost(url);
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("taskType", taskType));
            params.add(new BasicNameValuePair("msgType", msgType));
            params.add(new BasicNameValuePair("uid", uid));
            params.add(new BasicNameValuePair("seq", seq));
            httppost.setEntity(new UrlEncodedFormEntity(params));
            response = httpClient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == 200) {
                rs = HttpResponseParser.getResponseContent(response);
            } else {
                rs = "";
            }
        } catch (Exception ex) {
            logger.error(url + " JettyClient send error!" + ex.getMessage() + "|" + ex.getLocalizedMessage());
            return "";
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException ex) {
                logger.error(ex.getMessage(), ex);
            }
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
        return rs;
    }

    public String postSendReturnContent(String url, HashMap<String, String> paramsMap) {
        url = getRightUrl(url);
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String rs = "";
        try {
            httpClient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost(url);
            List<NameValuePair> params = new ArrayList<>();
            for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            httppost.setEntity(new UrlEncodedFormEntity(params));
            response = httpClient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == 200) {
                rs = HttpResponseParser.getResponseContent(response);
            } else {
                rs = "";
            }
        } catch (Exception ex) {
            logger.error(url + " JettyClient send error!" + ex.getMessage() + "|" + ex.getLocalizedMessage());
            return "";
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException ex) {
                logger.error(ex.getMessage(), ex);
            }
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
        return rs;
    }

    public boolean postSendReturnFile(String url, HashMap<String, String> paramsMap, String filePath) {
        url = getRightUrl(url);
        boolean flag = false;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost(url);
            List<NameValuePair> params = new ArrayList<>();
            for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            httppost.setEntity(new UrlEncodedFormEntity(params));
            response = httpClient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == 200) {
                System.out.println("ok");
                HttpResponseParser.getResponseFiles(response, filePath);
                System.out.println("finish one");
                flag = true;
            }
        } catch (Exception ex) {
            logger.error(url + " JettyClient send error!" + ex.getMessage() + "|" + ex.getLocalizedMessage());
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException ex) {
                logger.error(ex.getMessage(), ex);
            }
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
        return flag;
    }

    //get提交，返回文件
    public boolean getSendReturnFile(String url, String filePath) {
        boolean flag = false;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = HttpClients.createDefault();
            HttpGet httpget = new HttpGet(url);
            response = httpClient.execute(httpget);
            StatusLine st = response.getStatusLine();
            if (st.getStatusCode() == 200) {
                HttpResponseParser.getResponseFile(response, filePath);
                flag = true;
            }
        } catch (Exception ex) {
            logger.error(url + " JettyClient get send error!" + ex.getMessage() + "|" + ex.getLocalizedMessage());
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException ex) {
                logger.error(ex.getMessage(), ex);
            }
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
        return flag;
    }

    //get提交，返回content
    public String getSendReturnContent(String url) {
        String content = "";
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = HttpClients.createDefault();
            HttpGet httpget = new HttpGet(url);
            response = httpClient.execute(httpget);
            StatusLine st = response.getStatusLine();
            if (st.getStatusCode() == 200) {
                content = HttpResponseParser.getResponseContent(response);
            } else {
                content = "";
            }
        } catch (Exception ex) {
            logger.error(url + " JettyClient get send error!" + ex.getMessage() + "|" + ex.getLocalizedMessage());
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException ex) {
                logger.error(ex.getMessage(), ex);
            }
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
        return content;
    }

    public String getRightUrl(String url) {
        if (url.startsWith("http://")) {
            if (!url.endsWith("/")) {
                url = url + "/";
            }
        } else if (!url.startsWith("http://")) {
            if (!url.endsWith("/")) {
                url = "http://" + url + "/";
            } else {
                url = "http://" + url;
            }
        }
        return url;
    }
}
